<template>
<div style="height: calc(100vh - 223px);">
  <div style="border: red;">
      <ArtTableHeader v-model:columns="columnChecks" @refresh="handleRefresh">
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" :loading="loading">新增</ElButton>
          <ElButton type="warning" @click="batchGenerateFields" :loading="loading">生成</ElButton>
        </template>
      </ArtTableHeader>
  </div>
  
  <div style="height: calc(100% - 38px);">
	<ArtTable
      ref="tableRef"
      row-key="id"
      :loading="loading"
      :data="tableData"
      :currentPage="pagination.currentPage"
      :pageSize="pagination.pageSize"
      :total="pagination.total"
      :marginTop="10"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
	  :pagination="true"
	  :height="'100%'"
    >
      <template #default>
        <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
      </template>
    </ArtTable>
  </div>
  
  <!-- 元数据字段编辑弹窗 -->
  <ElDialog
    v-model="dialogFieldVisible"
    :title="fieldDialogTitle"
    width="40%"
    align-center
	:close-on-click-modal="false"
	:draggable="true"
  >
    <ElForm ref="fieldFormRef" :model="formData" :rules="fieldRules" label-width="135px">
		
		<ElRow :gutter="20">
			<ElCol :span="12">
				<ElFormItem label="显示标签" prop="label">
				  <ElInput v-model="formData.label" placeholder="显示标签"></ElInput>
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="列名" prop="name">
					<ElInput v-model="formData.name" placeholder="列名"></ElInput>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20">
			<ElCol :span="12">
				<ElFormItem label="物理字段名" prop="fieldName">
				  <ElInput v-model="formData.fieldName" placeholder="物理字段名"></ElInput>
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="物理字段备注" prop="fieldRemark">
					<ElInput v-model="formData.fieldRemark" placeholder="物理字段备注"></ElInput>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20">
			<ElCol :span="12">
				<ElFormItem label="栅格列数" prop="span" >
				  <ElInputNumber
				    v-model="formData.span"
				    :min="0"
					:max="24"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="显示顺序" prop="sort" >
				  <ElInputNumber
				    v-model="formData.sort"
				    :min="0"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20">
			<ElCol :span="12">
				<ElFormItem label="是否显示" prop="isVisible">
				  <ElSelect v-model="formData.isVisible">
				    <ElOption label="是" value="0" />
				    <ElOption label="否" value="1" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="字段类型" prop="dataType">
				  <ElSelect v-model="formData.dataType">
				    <ElOption label="字符串" value="String" />
				    <ElOption label="字节(8位)" value="Byte" />
				    <ElOption label="短整型(16位)" value="Short" />
				    <ElOption label="整型(32位)" value="Integer" />
				    <ElOption label="长整型(64位)" value="Long" />
				    <ElOption label="单精度浮点" value="Float" />
				    <ElOption label="双精度浮点型" value="Double" />
				    <ElOption label="布尔" value="Boolean" />
					<ElOption label="日期/时间" value="Date" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20">
			<ElCol :span="12">
				<ElFormItem :label="rule.type=='form'?'标签宽度':'列宽'" prop="width" >
				  <ElInputNumber
				    v-model="formData.width"
				    :min="0"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="控件类型" prop="controlType">
					<ElSelect
				        v-model="formData.controlType"
				        placeholder="请选择控件类型"
				        clearable
				        filterable
				        class="w-full"
				      >
				        <!-- 基础输入控件 -->
				        <ElOptionGroup label="输入类" v-if="formData.dataType!='Date'">
				          <ElOption
				            label="单行文本"
				            value="Input"
				          />
				          <ElOption
				            label="多行文本"
				            value="Textarea"
				          />
				          <ElOption
				            label="密码输入"
				            value="Password"
				          />
				        </ElOptionGroup>
				  
				        <!-- 选择类控件 -->
				        <ElOptionGroup label="选择类" v-if="formData.dataType!='Date'">
				          <ElOption
				            label="下拉选择"
				            value="Select"
				          />
						  
						  <ElOption
						    label="树形选择"
						    value="TreeSelect"
						  />
				          <ElOption
				            label="复选框"
				            value="Checkbox"
				          />
				          <ElOption
				            label="单选框"
				            value="Radio"
				          />
				          <ElOption
				            label="开关"
				            value="Switch"
				          />
				        </ElOptionGroup>
				  
				        <!-- 日期时间类 -->
				        <ElOptionGroup label="日期时间" v-if="formData.dataType=='Date'">
				          <ElOption
				            label="日期选择"
				            value="DatePicker"
				          />
				          <ElOption
				            label="时间选择"
				            value="TimePicker"
				          />
				          <ElOption
				            label="日期时间"
				            value="DateTimePicker"
				          />
				        </ElOptionGroup>
				  
				        <!-- 数字输入类 -->
				        <ElOptionGroup label="数字输入" v-if="['Short','Integer','Long','Float','Double'].includes(formData.dataType)">
				          <ElOption
				            label="数字输入框"
				            value="InputNumber"
				          />
				          <ElOption
				            label="滑块"
				            value="Slider"
				          />
				          <ElOption
				            label="评分"
				            value="Rate"
				          />
				        </ElOptionGroup>
				  
				        <!-- 高级控件 -->
				        <ElOptionGroup label="其他控件" v-if="formData.dataType!='Date'">
				          <ElOption
				            label="颜色选择"
				            value="ColorPicker"
				          />
				          <ElOption
				            label="文件上传"
				            value="Upload"
				          />
				          <ElOption
				            label="级联选择"
				            value="Cascader"
				          />
				        </ElOptionGroup>
					</ElSelect>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['Textarea','Input','Long','Float','Double'].includes(formData.controlType)">
			<ElCol :span="12">
				<ElFormItem label="最小长度" prop="min">
				  <ElInputNumber
				    v-model="formData.min"
				    :min="0"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="最大长度" prop="max">
				  <ElInputNumber
				    v-model="formData.max"
				    :min="0"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['InputNumber'].includes(formData.controlType)">
			<ElCol :span="12">
				<ElFormItem label="步进" prop="step">
				  <ElInputNumber
				    v-model="formData.step"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="精度" prop="precision">
				  <ElInputNumber
				    v-model="formData.precision"
				    :min="0"
				    controls-position="right"
					style="width: 100%;"
				  />
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20">
			<ElCol :span="12">
				<ElFormItem label="读写权限" prop="rw">
				  <ElSelect v-model="formData.rw">
					  <ElOption label="无" value="n" />
				    <ElOption label="只读" value="r" />
				    <ElOption label="读写" value="rw" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="允许空值" prop="isNullable">
				  <ElSelect v-model="formData.isNullable">
				    <ElOption label="可空" value="0" />
				    <ElOption label="必填" value="1" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['Select','Checkbox','Radio','Switch','TreeSelect'].includes(formData.controlType)">
			<ElCol :span="12">
				<ElFormItem label="选项来源" prop="mapping" >
				  <ElSelect v-model="formData.mapping">
					<ElOption label="字典" value="dict" />
					<ElOption label="自定义" value="remote" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="是否多选" prop="multiple" >
				  <ElSelect v-model="formData.multiple" :disabled="formData.controlType!='Select' && formData.controlType!='TreeSelect'">
					  <ElOption label="单选" value="0" />
					  <ElOption label="多选" value="1" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['TreeSelect'].includes(formData.controlType)">
			<ElCol :span="12">
				<ElFormItem label="选择任意级别" prop="checkStrictly" >
				  <ElSelect v-model="formData.checkStrictly">
					<ElOption label="任意级别" value="0" />
					<ElOption label="只有子节点可被选择" value="1" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
			<ElCol :span="12">
				<ElFormItem label="筛选选项" prop="filterable" >
				  <ElSelect v-model="formData.filterable">
					<ElOption label="禁用" value="0" />
					<ElOption label="启用" value="1" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['Select','Checkbox','Radio','Switch','TreeSelect'].includes(formData.controlType) && formData.mapping=='dict'">
		  <ElCol :span="24">
		  	<ElFormItem :label="formData.mapping=='dict' ?'字典标识' : '远程地址' " prop="mappingKey">
		  		<ElInput v-model="formData.mappingKey" :placeholder="formData.mapping=='dict' ?'字典标识' : '远程地址' "></ElInput>
		  	</ElFormItem>
		  </ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['DatePicker','TimePicker','DateTimePicker'].includes(formData.controlType)">
		  <ElCol :span="12">
		  	<ElFormItem label="时间/日期格式" prop="displayFormat">
		  		<ElInput v-model="formData.displayFormat" placeholder="时间/日期格式"></ElInput>
		  	</ElFormItem>
		  </ElCol>
		  <ElCol :span="12">
		  	<ElFormItem label="显示类型" prop="dateType" v-if="['DatePicker'].includes(formData.controlType)">
		  	  <ElSelect v-model="formData.dateType">
		  		<ElOption label="年" value="year"  />
				<ElOption label="多年" value="years"v-if="['DatePicker'].includes(formData.controlType)" />
				<ElOption label="月" value="month" />
				<ElOption label="多月" value="months" v-if="['DatePicker'].includes(formData.controlType)"/>
		  		<ElOption label="日期" value="date" />
				<ElOption label="多个日期" value="dates" v-if="['DatePicker'].includes(formData.controlType)"/>
				<ElOption label="日期时间" value="datetime" />
				<ElOption label="周" value="week" />
				<ElOption label="日期时间范围" value="datetimerange" />
				<ElOption label="日期范围" value="daterange" />
				<ElOption label="月份范围" value="monthrange" v-if="['DatePicker'].includes(formData.controlType)"/>
				<ElOption label="年份范围" value="yearrange" v-if="['DatePicker'].includes(formData.controlType)"/>
		  	  </ElSelect>
		  	</ElFormItem>
			
			<ElFormItem label="时间范围选择" prop="isRange" v-else-if="['TimePicker'].includes(formData.controlType)">
			  <ElSelect v-model="formData.isRange">
				<ElOption label="是" value="0" />
				<ElOption label="否" value="1" />
			  </ElSelect>
			</ElFormItem>
		  </ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['Textarea','Input'].includes(formData.controlType)">
		  <ElCol :span="24">
		  	<ElFormItem label="正则表达式" prop="pattern">
		  		<ElInput v-model="formData.pattern" placeholder="请输入正则表达式"></ElInput>
		  	</ElFormItem>
		  </ElCol>
		</ElRow>
		
		<ElRow :gutter="20" v-if="['TreeSelect','Select'].includes(formData.controlType)">
		  <ElCol :span="24">
		  	<ElFormItem label="空值配置" prop="emptyValues">
		  		<ElInput v-model="formData.emptyValues" placeholder="请输入空值配置(多个请用英文逗号分隔)"></ElInput>
		  	</ElFormItem>
		  </ElCol>
		</ElRow>
		
		<ElRow :gutter="20" >
			<ElCol :span="12">
				<ElFormItem label="是否为数组" prop="isArray" >
				  <ElSelect v-model="formData.isArray">
					<ElOption label="否" value="0" />
					<ElOption label="是" value="1" />
				  </ElSelect>
				</ElFormItem>
			</ElCol>
			
			<ElCol :span="12">
				<ElFormItem label="默认值" prop="defaultValue">
					<ElInput v-model="formData.defaultValue" placeholder="请输入默认值"></ElInput>
				</ElFormItem>
			</ElCol>
			
		</ElRow>
    </ElForm>
    
	<template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogFieldVisible = false" :loading="loading">取消</ElButton>
        <ElButton type="primary" @click="handleFieldSubmit" :loading="loading">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</div>
</template>

<script setup lang="ts">
  import { h, ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
  import { ElDialog, FormInstance, ElTag, ElTableColumn } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { SearchChangeParams, SearchFormItem } from '@/types'
  import { useCommon } from '@/composables/useCommon'
  import { useWindowSize } from '@vueuse/core'
  import { RuleService } from '@/api/data-rule/ruleApi'
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'RuleFieldTable' })
  
  const rule = ref<any>();
  const props = defineProps({
  	data: {
  		type: Object,
  		default: () => {}
  	},
  })
  
  // 弹窗控制
  const dialogFieldType = ref('add')
  const dialogFieldVisible = ref(false)
  
  // 计算弹窗标题
  const fieldDialogTitle = computed(() => 
    dialogFieldType.value === 'add' ? '添加字段' : '编辑字段'
  )
  
  const loading = ref(false)
  
  // 分页设置
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })
  
  const typeMap: Record<string, string> = {
    'Input': '输入框',
    'Textarea': '多行文本',
    'Password': '密码输入',
    'Select': '下拉选择',
	'TreeSelect':'树形选择',
	'Checkbox': '复选框',
	'Radio': '单选框',
	'Switch': '开关',
	'DatePicker': '日期选择',
	'TimePicker': '时间选择',
	'DateTimePicker': '日期时间',
	'InputNumber': '数字输入框',
	'Slider': '滑块',
	'Rate': '评分',
	'ColorPicker': '颜色选择',
	'Upload': '文件上传',
  }
  
  // 表格实例引用
  const tableRef = ref()
  // 表格数据
  const tableData = ref<any[]>([])
  // 选中的行数据
  const selectedRows = ref<any[]>([])
  // 表单引用
  const fieldFormRef = ref<FormInstance>()
  
  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
	{
	  prop: 'label', 
	  label: '显示标签',
	  showOverflowTooltip: true
	},
    { 
      prop: 'name', 
      label: '列名',
      width: 120,
	  showOverflowTooltip: true
    },
    {
      prop: 'dataType',
      label: '数据类型',
      width: 80,
	  align:'center',
	  showOverflowTooltip: true,
      formatter: (row: any) => {
        const typeMap: Record<string, string> = {
          'String': '字符串',
          'Byte': '字节',
          'Short': '短整型',
          'Integer': '整型',
          'Long': '长整型',
          'Float': '单精度浮点',
          'Double': '双精度浮点',
          'Boolean': '布尔',
          'Date': '日期'
        }
        return typeMap[row.dataType] || row.dataType
      }
    },
    {
      prop: 'fieldName',
      label: '物理字段名',
      width: 120,
	  showOverflowTooltip: true
    },
    {
      prop: 'fieldRemark',
      label: '物理字段备注',
      width: 120,
      showOverflowTooltip: true
    },
    {
      prop: 'tableName',
      label: '物理表名',
      width: 120,
	  showOverflowTooltip: true
    },
    {
      prop: 'sort',
      label: '显示顺序',
	  width: 80,
	  align:'center',
    },
    {
      prop: 'isVisible',
      label: '是否显示',
      width: 80,
	  align:'center',
      formatter: (row: any) => {
		return h(ElTag, { type: row.isVisible === '0' ? 'success' : 'info' }, () => {
		   return row.isVisible === '0' ? '显示' : '隐藏'
		})
      }
    },
	{
	  prop: 'rw',
	  label: '读写权限',
	  width: 80,
	  align:'center',
	  formatter: (row: { rw: 'n' | 'r' | 'w' | 'rw' }) => {
	    type TagType = 'success' | 'warning' | 'danger' | 'info'
	    const rwMap = {
	      'n': { text: '无权限', type: 'danger' } as const,
	      'r': { text: '只读', type: 'warning' } as const,
	      'w': { text: '只写', type: 'info' } as const,
	      'rw': { text: '读写', type: 'success' } as const
	    }
	    const config = rwMap[row.rw] ?? { text: '-', type: 'info' } as const
	    return h(ElTag, { 
	      type: config.type satisfies TagType 
	    }, () => {
			return config.text
		})
	  }
	},
    {
      prop: 'controlType',
      label: '控件类型',
	  width: 80,
	  align:'center',
      formatter: (row: any) => {
        return typeMap[row.controlType] || row.controlType
      }
    },
    {
      prop: 'span',
      label: '栅格列数',
	  width: 80,
	  align:'center'
    },	
	{
	  prop: 'mapping',
	  label: '映射类型',
	  width: 80,
	  align:'center',
	  formatter: (row: { mapping: 'none' | 'const' | 'dict' | 'cache' | string }) => {
		const map: Record<'none' | 'const' | 'dict' | 'cache', string> = {
		  'none': '无',
		  'const': '常量',
		  'dict': '字典',
		  'cache': '缓存'
		}
		return map[row.mapping as 'none' | 'const' | 'dict' | 'cache'] || row.mapping
	  }
	},
    {
      prop: 'operation',
      label: '操作',
      width: 110,
	  fixed: 'right',
      formatter: (row: any) => {
        return h('div', [
          h(ArtButtonTable, {
            type: 'edit',
            onClick: () => showDialog('edit', row)
          }),
          h(ArtButtonTable, {
            type: 'delete',
            onClick: () => batchRemoveFields(row.id)
          })
        ])
      }
    }
  ])
  
  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }
  
  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getFieldList()
  }
  
  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.currentPage = newCurrentPage
    getFieldList()
  }
  
  const handleRefresh = () => {
    getFieldList()
  }
  
  // 获取字段列表（添加安全校验）
  const getFieldList = async () => {
    // 添加规则ID校验
    if (!rule.value?.id) {
      console.warn('规则ID缺失，终止请求')
      tableData.value = []
      pagination.total = 0
      return
    }
    
    loading.value = true
    try {
      const { currentPage, pageSize } = pagination
      const { list, totalRow } = await RuleService.getFieldByPages({
        pageNumber: currentPage,
        pageSize: pageSize,
		query: {
			ruleId: rule.value.id
		}
      })
      tableData.value = list
      Object.assign(pagination, { currentPage, pageSize, total: totalRow })
    } catch (error) {
      console.error('获取字段列表失败:', error)
      ElMessage.error('数据加载失败')
    } finally {
      loading.value = false
    }
  }
  
  const formData = ref({
	id: '',
	ruleId: '',
    label: '',
    name: '',
    fieldName: '',
    fieldRemark: '',
    sortable: '1',
    sort: 0,
    isVisible: '0',
    dataType: 'String',
    width: 100,
    controlType: '',
    mapping: 'none',
    isNullable: '0',
    displayFormat: '',
    rw: 'rw',
    mappingInfo: '',
    mappingKey: '',
	min:0,
	max:0,
	rows:2,
	multiple:'0',
	span:24,
	checkStrictly:'0',
	filterable:'0',
	step:1,
	precision:0,
	dateType:'year',
	isRange:'1',
	pattern:'',
	emptyValues:'',
	defaultValue:undefined,
	isArray:'0'
  })
  
  // 修复验证规则（使用函数形式）
  const fieldRules = reactive<FormRules>({
	label: [
	  { required: true, message: '请输入显示标签', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
    name: [
      { required: true, message: '请输入列称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
	fieldName: [
	  { required: true, message: '请输入物理字段名', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
	dataType: [
	  { required: true, message: '请选择字段类型', trigger: 'blur' }
	],
	span: [
	  { required: true, message: '请输入栅格占据的列数', trigger: 'blur' }
	],
	sort: [
	  { required: true, message: '请输入显示顺序', trigger: 'blur' }
	],
	isVisible: [
	  { required: true, message: '请选择是否显示', trigger: 'blur' }
	],
	width: [
	  { required: true, message: '请输入显示标签宽度', trigger: 'blur' }
	],
	controlType: [
	  { required: true, message: '请选择渲染控件类型', trigger: 'blur' }
	],
	isNullable: [
	  { required: true, message: '请选择是否必填', trigger: 'blur' }
	],
	rw: [
	  { required: true, message: '请选择读写权限', trigger: 'blur' }
	],
	min: [
	  { required: true, message: '请输入最小字符长度', trigger: 'blur' }
	],
	max: [
	  { required: true, message: '请输入最大字符长度', trigger: 'blur' }
	],
	multiple: [
	  { required: true, message: '请选择下拉值是否可以多选', trigger: 'blur' }
	],
	mapping: [
	  { required: true, message: '请选择下拉值来源', trigger: 'blur' }
	],
	checkStrictly: [
	  { required: true, message: '请选择是否支持选择任意级别', trigger: 'blur' }
	],
	filterable: [
	  { required: true, message: '请选择是否支持筛选选项', trigger: 'blur' }
	],
	displayFormat: [
	  { required: true, message: '请输入时间/日期格式', trigger: 'blur' }
	],
	step: [
	  { required: true, message: '请输入步进值', trigger: 'blur' }
	],
	precision: [
	  { required: true, message: '请输入精度值', trigger: 'blur' }
	],
	dateType: [
	  { required: true, message: '请输入选择日期显示类型', trigger: 'blur' }
	],
	isRange: [
	  { required: true, message: '请选择是否为时间范围', trigger: 'blur' }
	],
	isArray: [
	  { required: true, message: '请选择值是否为数组', trigger: 'blur' }
	],
    mappingKey: [
      { 
        required: formData.value.mapping === 'dict' || formData.value.mapping === 'cache',
        message: '请输入映射标识', 
        trigger: 'blur'
      }
    ],
    mappingInfo: [
      { 
        required: formData.value.mapping === 'const',
        message: '请输入映射内容', 
        trigger: 'blur'
      }
    ],
  })
  
  // 显示字段编辑弹窗
  const showDialog = (type: string, row?: any) => {
    dialogFieldType.value = type
    dialogFieldVisible.value = true
    nextTick(() => {
      if (fieldFormRef.value) {
        fieldFormRef.value.resetFields()
		fillFormData(row);
      }
    })
  }
  
  const fillFormData = (row?: any) => {
    // 重置表单
    formData.value = {
	  id: '',
	  ruleId: rule.value.id,
      label: '',
      name: '',
      fieldName: '',
      fieldRemark: '',
      sortable: '1',
      sort: 0,
      isVisible: '0',
      dataType: 'String',
      width: 100,
      controlType: '',
      mapping: 'none',
      isNullable: '0',
      displayFormat: '',
      rw: 'rw',
      mappingInfo: '',
      mappingKey: '',
	  min:0,
	  max:0,
	  rows:2,
	  multiple:'0',
	  span:24,
	  checkStrictly:'0',
	  filterable:'0',
	  step:1,
	  precision:0,
	  dateType:'year',
	  isRange:'1',
	  pattern:'',
	  emptyValues:'',
	  defaultValue:undefined,
	  isArray:'0'
    };
  
    if (row) {
      Object.assign(formData.value, {
		id: row.id || '',
		ruleId: row.ruleId || rule.value.id,
        label: row.label || '',
        name: row.name || '',
        fieldName: row.fieldName || '',
        fieldRemark: row.fieldRemark || '',
        sortable: row.sortable !== undefined ? String(row.sortable) : '1',
        sort: Number(row.sort) || 0,
        isVisible: row.isVisible !== undefined ? String(row.isVisible) : '0',
        dataType: row.dataType || 'String',
        width: Number(row.width) || 100,
        controlType: row.controlType || '',
        mapping: row.mapping || 'none',
        isNullable: row.isNullable !== undefined ? String(row.isNullable) : '0',
        displayFormat: row.displayFormat || '',
        rw: row.rw || 'rw',
		multiple: row.multiple,
        mappingInfo: row.mappingInfo || '',
        mappingKey: row.mappingKey || '',
		min: Number(row.min),
		max: Number(row.max),
		rows: Number(row.rows) ,
		span: Number(row.span) ,
		checkStrictly:row.checkStrictly,
		filterable:row.filterable,
		step:row.step,
		precision:row.precision,
		dateType:row.dateType,
		isRange:row.isRange,
		pattern:row.pattern,
		emptyValues:row.emptyValues,
		defaultValue:row.defaultValue,
		isArray:row.isArray,
      });
    }
  };
  
  // 字段编辑提交
  const handleFieldSubmit = async () => {
    if (!fieldFormRef.value) return
    await fieldFormRef.value.validate(async (valid) => {
      if (valid) {
  		loading.value = true
        try {
  			await RuleService.saveField(formData.value);
  			const message = dialogFieldType.value === 'add' ? '新增成功' : '修改成功'
  			ElMessage.success(message)
  			getFieldList();
        } catch {
  			ElMessage.error(`操作失败`)
        } finally {
  			dialogFieldVisible.value = false
  			loading.value = false
  		}
      }
    })
  }
  
  // 批量生成字段
  const batchGenerateFields = async () => {
    ElMessageBox.confirm('确定批量生成字段吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 添加规则ID校验
      if (!rule.value?.id) {
        ElMessage.warning('规则ID缺失，无法生成字段')
        return
      }
      
      try {
        loading.value = true
        await RuleService.generateFields(rule.value.id);
        getFieldList();
        ElMessage.success('批量生成成功')
      } catch (e) {
        console.error(e)
        ElMessage.error('生成失败')
      } finally {
        loading.value = false
      }
    })
  }
  
  // 批量删除字段（优化ID处理）
  const batchRemoveFields = (ids: string[] | string) => {
    // 转换为数组格式
    const idsArray = Array.isArray(ids) ? ids : [ids]
    
    if (idsArray.length === 0) {
      ElMessage.warning('请选择要删除的字段')
      return
    }
    
    ElMessageBox.confirm('确定移除这些字段吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      try {
        loading.value = true
        await RuleService.deleteFields(idsArray)
        fillFormData()
        getFieldList()
        ElMessage.success('删除成功')
      } catch (e) {
        console.error(e)
        ElMessage.error('删除失败')
      } finally {
        loading.value = false
      }
    })
  }
  
  // 监听props变化
  watch(props, () => {
    rule.value = props.data
    getFieldList()
  }, { immediate: true, deep: true })
</script>